package net.blank.bitmapUtil
{
	
	import flash.display.BitmapData;
	import flash.display.Shape;
	import flash.geom.Rectangle;
	
	import net.blank.bitmapOperation.BitmapDraw;
	import net.blank.ui.core.Arrange;
	
	/**
	 * 图像合成器
	 * @author blank
	 * 
	 */
	public class BitmapComposer
	{
		/**
		 * 图像合成
		 * @param bmpDatas 图像列表
		 * @param rects 对应的绘制区域
		 * @param aligns 相对于最终绘制区域的对象方式,参照 Arrange 类
		 * @param innerScaleRects 对应的九格缩放区域
		 * @return 
		 * 
		 */
		public static function composeBitmapData(bmpDatas:Vector.<BitmapData>,rects:Vector.<Rectangle>=null,aligns:Vector.<Vector.<String>>=null,innerScaleRects:Vector.<Rectangle>=null):BitmapData{
			var i:int, len:int = bmpDatas.length;
			
			var rl:int=rects ? rects.length : 0;
			var al:int=aligns ? aligns.length : 0;
			var il:int=innerScaleRects ? innerScaleRects.length : 0;
			
			/*计算绘制完成后的最终区域*/
			var resultRect:Rectangle = new Rectangle();
			for(i=0;i < len;i++){
				if(i < rl && rects[i]){
					resultRect = resultRect.union(rects[i]);
				}else{
					resultRect = resultRect.union(bmpDatas[i].rect);
				}
			}
			
			var bmpData:BitmapData;
			var drawRect:Rectangle;
			
			var canvas:Shape = new Shape();
			for(i=0;i < len;i++){
				bmpData = bmpDatas[i];
				
				if(i < rl && rects[i]){
					drawRect = rects[i];
				}else if(i < al && aligns[i]){
					drawRect = new Rectangle();
					switch(aligns[i][0]){
						case Arrange.LEFT:
						default:
							drawRect.x = 0;
							break;
						case Arrange.CENTER:
							drawRect.x = resultRect.width - bmpData.width >> 1;
							break;
						case Arrange.RIGHT:
							drawRect.x = resultRect.width - bmpData.width;
							break;
					}
					
					switch(aligns[i][1]){
						case Arrange.TOP:
						default:
							drawRect.y = 0;
							break;
						case Arrange.MIDDLE:
							drawRect.y = resultRect.height - bmpData.height >> 1;
							break;
						case Arrange.BOTTOM:
							drawRect.y = resultRect.height - bmpData.height;
							break;
						break;
					}
					drawRect.width = bmpData.width;
					drawRect.height = bmpData.height;
				}
				
				if(i < il && innerScaleRects[i]){
					BitmapDraw.drawScale9Grid(canvas.graphics, bmpData, drawRect, innerScaleRects[i]);
				}else{
					BitmapDraw.drawBitmap(canvas.graphics, bmpData, drawRect);
				}
			}
			var resultBitmapData:BitmapData = new BitmapData(resultRect.width, resultRect.height, true, 0);
			resultBitmapData.draw(canvas);
			
			return resultBitmapData;
		}
	}
}